package dp;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

public class P542 {
    public int[][] updateMatrix(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;

        int[][] result = new int[m][n];
        for (int i = 0; i < m; i++) {
            int[] row = new int[n];
            Arrays.fill(row, -1);
            result[i] = row;
        }
        Queue<int[]> queue = new ArrayDeque<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 0) {
                    queue.add(new int[]{i, j, 0});
                }
            }
        }
        int[][] directions = new int[][]{
                {1, 0}, {-1, 0}, {0, 1}, {0, -1}
        };
        while (!queue.isEmpty()) {
            int[] pos = queue.poll();
            if (result[pos[0]][pos[1]] == -1) {//未设值
                result[pos[0]][pos[1]] = pos[2];
                //添加附近的元素
                for (int[] direct : directions) {
                    int nx = direct[0] + pos[0];
                    int ny = direct[1] + pos[1];
                    if (0 <= nx && nx < m && 0 <= ny && ny < n && result[nx][ny] == -1) {
                        queue.offer(new int[]{nx, ny, pos[2] + 1});
                    }
                }
            }
        }
        return result;
    }
}
